package com.hugang.juc.lock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 手写自旋锁示例
 *
 * @author hg
 * @date 2020/8/25 11:14
 */
public class SpinLockDemo {

    //原子引用线程
    AtomicReference<Thread> reference = new AtomicReference<Thread>();

    /**
     * 自旋锁加锁
     */
    public void myLock(){
        Thread thread = Thread.currentThread();
        System.out.println(thread.getName() +" ---> 尝试加锁...");

        //一开始reference中的value为null，因此只有期望值为null且当前时间点内存中的此值也为null时才能设置成功，就跳出循环。否则一直循环比较并交换
        while (!reference.compareAndSet(null,thread)){

        }
        System.out.println(thread.getName() +" ---> 加锁成功");
    }

    /**
     * 解锁
     */
    public void myUnlock(){
        Thread thread = Thread.currentThread();
        //只有当reference中的value为当前线程时，才能解锁成功。解锁成功之后，将value置为null，即解锁，其他线程就可以通过自旋成功加锁
        while (!reference.compareAndSet(thread,null)){

        }
        System.out.println(thread.getName() +" ---> 解锁成功");

    }

    public static void main(String[] args) {
        SpinLockDemo lock = new SpinLockDemo();
        //线程t1加锁
        new Thread(()->{
            lock.myLock();
            try {
                TimeUnit.SECONDS.sleep(5);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.myUnlock();
            }
        },"t1").start();

        try {
            TimeUnit.SECONDS.sleep(1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        //线程t2加锁
        new Thread(()->{
            lock.myLock();
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.myUnlock();
            }
        },"t2").start();
    }

}
